package com.thinkgem.jeesite.modules.act.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.javax.el.ExpressionFactory;
import org.activiti.engine.impl.javax.el.ValueExpression;
import org.activiti.engine.impl.juel.ExpressionFactoryImpl;
import org.activiti.engine.impl.juel.SimpleContext;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.impl.pvm.process.TransitionImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.act.dao.ActDao;

@Service
@Transactional(readOnly = true)
public class ActCodeService extends BaseService implements
		ActCodeServiceInterface {

	@Autowired
	private ActDao actDao;

	@Autowired
	private ProcessEngineFactoryBean processEngine;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private FormService formService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private IdentityService identityService;

	/**
	 * 中止流程(特权人直接审批通过等)
	 * 
	 * @param taskId
	 *            任务id
	 */
	@Override
	@Transactional(readOnly = false)
	public void endProcess(String taskId) throws Exception {
		ActivityImpl endActivity = findActivitiImpl(taskId, "end");

		turnTransition(taskId, endActivity.getId(), null);

	}

	/**
	 * 根据任务ID获取流程定义
	 * 
	 * @param taskId
	 *            任务ID
	 * @return
	 * @throws Exception
	 */
	@Override
	public ProcessDefinitionEntity findProcessDefinitionEntityByTaskId(
			String taskId) throws Exception {
		// 取得流程定义
		ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
				.getDeployedProcessDefinition(findTaskById(taskId)
						.getProcessDefinitionId());

		if (processDefinition == null) {
			throw new Exception("流程定义未找到!");
		}

		return processDefinition;
	}

	/**
	 * 流程转向操作
	 * 
	 * @param taskId
	 *            当前任务ID
	 * @param activityId
	 *            目标节点任务ID(内部标识)
	 * @param variables
	 *            流程变量
	 * @throws Exception
	 */
	@Override
	@Transactional(readOnly = false)
	public void turnTransition(String taskId, String activityId,
			Map<String, Object> variables) throws Exception {
		// 当前节点
		ActivityImpl currActivity = findActivitiImpl(taskId, null);
		// 清空当前流向
		List<PvmTransition> oriPvmTransitionList = clearTransition(currActivity);

		// 创建新流向
		TransitionImpl newTransition = currActivity.createOutgoingTransition();
		// 目标节点
		ActivityImpl pointActivity = findActivitiImpl(taskId, activityId);
		// 设置新流向的目标节点
		newTransition.setDestination(pointActivity);

		// 执行转向任务
		taskService.complete(taskId, variables);
		// 删除目标节点新流入
		pointActivity.getIncomingTransitions().remove(newTransition);

		// 还原以前流向
		restoreTransition(currActivity, oriPvmTransitionList);
	}

	/**
	 * 根据任务ID和节点ID获取活动节点 <br>
	 * 
	 * @param taskId
	 *            任务ID
	 * @param activityId
	 *            活动节点ID <br>
	 *            如果为null或""，则默认查询当前活动节点 <br>
	 *            如果为"end"，则查询结束节点 <br>
	 * 
	 * @return
	 * @throws Exception
	 */
	public ActivityImpl findActivitiImpl(String taskId, String activityId)
			throws Exception {
		// 取得流程定义
		ProcessDefinitionEntity processDefinition = findProcessDefinitionEntityByTaskId(taskId);

		// 获取当前活动节点ID
		if (org.apache.commons.lang3.StringUtils.isEmpty(activityId)) {
			activityId = findTaskById(taskId).getTaskDefinitionKey();
		}

		// 根据流程定义，获取该流程实例的结束节点
		if (activityId.toUpperCase().equals("END")) {
			for (ActivityImpl activityImpl : processDefinition.getActivities()) {
				List<PvmTransition> pvmTransitionList = activityImpl
						.getOutgoingTransitions();
				if (pvmTransitionList.isEmpty()) {
					return activityImpl;
				}
			}
		}

		// 根据节点ID，获取对应的活动节点
		ActivityImpl activityImpl = ((ProcessDefinitionImpl) processDefinition)
				.findActivity(activityId);

		return activityImpl;
	}

	/**
	 * 根据任务ID获得任务实例
	 * 
	 * @param taskId
	 * @return
	 * @throws Exception
	 */
	public TaskEntity findTaskById(String taskId) throws Exception {
		TaskEntity task = (TaskEntity) taskService.createTaskQuery()
				.taskId(taskId).singleResult();
		if (task == null) {
			throw new Exception("任务实例未找到!");
		}
		return task;
	}

	/**
	 * 转办流程
	 * 
	 * @param taskId
	 *            当前任务节点ID
	 * @param userCode
	 *            被转办人Code（帐号）
	 */
	@Override
	public void transferAssignee(String taskId, String userCode) {
		taskService.setAssignee(taskId, userCode);
	}

	/**
	 * 根据任务ID获取对应的流程实例
	 * 
	 * @param taskId
	 *            任务ID
	 * @return
	 * @throws Exception
	 */
	public ProcessInstance findProcessInstanceByTaskId(String taskId)
			throws Exception { // 找到流程实例
		ProcessInstance processInstance = runtimeService
				.createProcessInstanceQuery()
				.processInstanceId(findTaskById(taskId).getProcessInstanceId())
				.singleResult();
		if (processInstance == null) {
			throw new Exception("流程实例未找到!");
		}
		return processInstance;
	}

	/**
	 * 查询历史任务
	 * @param taskId （参数不可空）
	 * @param processInstanceID （参数不可空）
	 * @return 
	 * @author lgx
	 * Date:2016年3月30日；
	 */
	public HistoricTaskInstance findHistricTaskById(String taskId,String processInstanceID){
		return historyService.createHistoricTaskInstanceQuery().taskId(taskId)//创建历史任务实例查询
		.processInstanceId(processInstanceID).singleResult();
	}

	/**
	 * 
	 * 查询流程当前节点的下一步节点。
	 * 
	 * @param taskId
	 * 
	 * @return
	 * 
	 * @throws Exception
	 */
	public Map<String, FlowNode> findNextTask(String taskId) throws Exception {
		Map<String, org.activiti.bpmn.model.FlowNode> nodeMap = new HashMap<String, org.activiti.bpmn.model.FlowNode>();
		ProcessInstance processInstance = findProcessInstanceByTaskId(taskId);
		// 查询当前节点
		HistoricTaskInstance histask = findHistricTaskById(taskId,
				processInstance.getProcessInstanceId());
		// 查询流程定义 。
		BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance
				.getProcessDefinitionId());
		List<org.activiti.bpmn.model.Process> listp = bpmnModel.getProcesses();
		org.activiti.bpmn.model.Process process = listp.get(0);
		// 当前节点流定义
		FlowNode sourceFlowElement = (FlowNode) process.getFlowElement(histask
				.getTaskDefinitionKey());
		// 找到当前任务的流程变量
		List<HistoricVariableInstance> listVar = historyService
				.createHistoricVariableInstanceQuery()
				.processInstanceId(processInstance.getId()).list();
		iteratorNextNodes(process, sourceFlowElement, nodeMap, listVar);
		return nodeMap;
	}

	/**
	 * 查询流程当前节点的下一步节点。用于流程提示时的提示。
	 * 
	 * @param process
	 * @param sourceFlowElement
	 * @param nodeMap
	 * @param listVar
	 * @throws Exception
	 */
	private void iteratorNextNodes(org.activiti.bpmn.model.Process process,
			FlowNode sourceFlowElement, Map<String, FlowNode> nodeMap,
			List<HistoricVariableInstance> listVar) throws Exception {
		List<SequenceFlow> list = sourceFlowElement.getOutgoingFlows();
		for (SequenceFlow sf : list) {
			sourceFlowElement = (FlowNode) process.getFlowElement(sf
					.getTargetRef());
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(sf.getConditionExpression())) {
				ExpressionFactory factory = new ExpressionFactoryImpl();
				SimpleContext context = new SimpleContext();
				for (HistoricVariableInstance var : listVar) {
					context.setVariable(var.getVariableName(), factory
							.createValueExpression(var.getValue(), var
									.getValue().getClass()));
				}
				ValueExpression e = factory.createValueExpression(context,
						sf.getConditionExpression(), boolean.class);
				if ((Boolean) e.getValue(context)) {
					nodeMap.put(sourceFlowElement.getId(), sourceFlowElement);
					break;
				}
			}
			if (sourceFlowElement instanceof org.activiti.bpmn.model.UserTask) {
				nodeMap.put(sourceFlowElement.getId(), sourceFlowElement);
				break;
			} else if (sourceFlowElement instanceof org.activiti.bpmn.model.ExclusiveGateway) {
				iteratorNextNodes(process, sourceFlowElement, nodeMap, listVar);
			}
		}
	}

	// TODO:内部私有方法
	/**
	 * 清空指定活动节点流向
	 * 
	 * @param activityImpl
	 *            活动节点
	 * @return 节点流向集合
	 */
	@Transactional(readOnly = false)
	private List<PvmTransition> clearTransition(ActivityImpl activityImpl) {
		// 存储当前节点所有流向临时变量
		List<PvmTransition> oriPvmTransitionList = new ArrayList<PvmTransition>();
		// 获取当前节点所有流向，存储到临时变量，然后清空
		List<PvmTransition> pvmTransitionList = activityImpl
				.getOutgoingTransitions();
		for (PvmTransition pvmTransition : pvmTransitionList) {
			oriPvmTransitionList.add(pvmTransition);
		}
		pvmTransitionList.clear();

		return oriPvmTransitionList;
	}

	/**
	 * 还原指定活动节点流向
	 * 
	 * @param activityImpl
	 *            活动节点
	 * @param oriPvmTransitionList
	 *            原有节点流向集合
	 */
	@Transactional(readOnly = false)
	private void restoreTransition(ActivityImpl activityImpl,
			List<PvmTransition> oriPvmTransitionList) {
		// 清空现有流向
		List<PvmTransition> pvmTransitionList = activityImpl
				.getOutgoingTransitions();
		pvmTransitionList.clear();
		// 还原以前流向
		for (PvmTransition pvmTransition : oriPvmTransitionList) {
			pvmTransitionList.add(pvmTransition);
		}
	}

}
